<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');

/**
 * Contao Open Source CMS
 * Copyright (C) 2005-2010 Leo Feyer
 *
 * Formerly known as TYPOlight Open Source CMS.
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program. If not, please visit the Free
 * Software Foundation website at <http://www.gnu.org/licenses/>.
 *
 * PHP version 5
 * @copyright  certo web & design GmbH 2011 
 * @author     Yanick Witschi <yanick.witschi@certo-net.ch> 
 * @package    rapidmail_sync_recipients 
 * @license    LGPL
 * @filesource
 */
 

/**
 * Class RapidmailRecipientsSynchronizer 
 *
 * @copyright  certo web & design GmbH 2011 
 * @author     Yanick Witschi <yanick.witschi@certo-net.ch> 
 * @package    rapidmail_sync_recipients
 */
class RapidmailRecipientsSynchronizer extends Backend
{

	/**
	 * Initialize the object
	 */
	public function __construct()
	{
		parent::__construct();
	}
  
  
	/**
	 * Return the module state icon
	 * @param array
	 * @param string
	 * @param string
	 * @param string
	 * @param string
	 * @param string
	 * @return string
	 */
	public function getModuleState($row, $href, $label, $title, $icon, $attributes)
	{
		if($row['rm_sync_recipients_activate'] == 1)
		{
			return $this->generateImage('system/modules/rapidmail_sync_recipients/html/rm_active.png', $GLOBALS['TL_LANG']['tl_newsletter_channel']['rm_sync_recipients_module_active'], 'title="' . $GLOBALS['TL_LANG']['tl_newsletter_channel']['rm_sync_recipients_module_active'] . '"');
		}
      
		return $this->generateImage('system/modules/rapidmail_sync_recipients/html/rm_inactive.png', $GLOBALS['TL_LANG']['tl_newsletter_channel']['rm_sync_recipients_module_inactive'], 'title="' . $GLOBALS['TL_LANG']['tl_newsletter_channel']['rm_sync_recipients_module_inactive'] . '"');
	}
  
  
	/**
	 * Send a new recipient to rapidmail.de and log errors if there are any
	 * @param string
	 * @param string
	 * @param array
	*/ 
	public function sendNewRecipientToRapidmail($strEmail, $arrRecipients, $arrChannels)
	{
		foreach($arrChannels as $channel)
		{
			// get authentication data from tl_newsletter_channel with the sync mode set to ACTIVE
			$objRow = $this->Database->prepare("SELECT
													rm_sync_recipients_list_id AS list_id,
                                            		rm_sync_recipients_node_id AS node_id,
                                            		rm_sync_recipients_auth_key AS auth_key,
                                            		rm_sync_recipients_inform_error_mail AS sendErrorTo
                                          		FROM
                                            		tl_newsletter_channel
                                          		WHERE
                                            		id=?
                                          		AND
                                            		rm_sync_recipients_activate=?
                                         		")
                               		->limit(1)
                               		->execute($channel, 1);
  
			// if we don't get any row, the sync mode is disabled and we can continue to the next channel
			if($objRow->numRows < 1)
			{
				continue;
			}
  
			// try to connect and send data to rapidmail. throw an exception if there are any errors.
			try
			{
		        $this->import('Encryption');
		        $authkey = $this->Encryption->decrypt($objRow->auth_key);
		        $objRapidMail = new ContaoRapidMail($objRow->node_id, $objRow->list_id, $authkey);
		        $objRapidMail->add_recipient($strEmail);
		        $this->log('The e-mail adress "' . $strEmail . '" has successfully been synchronized to rapidmail.de (recipient list ID: ' . $objRow->list_id . ')!', 'RapidmailRecipientsSynchronizer sendNewRecipientToRapidmail()', TL_GENERAL);    
			}
			catch(Exception $e)
			{
				$this->logErrors('onSend', $e->getMessage(), $strEmail, $channel, $objRow->list_id, $objRow->sendErrorTo);
			}
		}
	}
  
  
	/**
	 * Delete a recipient from rapidmail.de and log errors if there are any
	 * @param string
	 * @param array
	 */ 
	public function removeRecipientFromRapidmail($strEmail, $arrChannels)
	{
	    /**
	     * yanick.witschi@certo-net.ch
	     * Array ( [0] => 2 [1] => 1 )
	     */
     
		foreach($arrChannels as $channel)
    	{
      		// get authentication data from tl_newsletter_channel with the sync mode set to ACTIVE
      		$objRow = $this->Database->prepare("SELECT
                                            		rm_sync_recipients_list_id AS list_id,
                                            		rm_sync_recipients_node_id AS node_id,
                                            		rm_sync_recipients_auth_key AS auth_key,
                                            		rm_sync_recipients_inform_error_mail AS sendErrorTo
                                          	FROM
                                            	tl_newsletter_channel
                                          	WHERE
                                            	id=?
                                          	AND
                                            	rm_sync_recipients_activate=?
                                         	")
                               		->limit(1)
                               		->execute($channel, 1);
  
			// if we don't get any row, the sync mode is disabled and we can continue to the next channel
			if($objRow->numRows < 1)
			{
				continue;
			}
  
			// try to connect and send data to rapidmail. throw an exception if there are any errors.
			try
			{
				$this->import('Encryption');
				$authkey = $this->Encryption->decrypt($objRow->auth_key);
				$objRapidMail = new ContaoRapidMail($objRow->node_id, $objRow->list_id, $authkey);
				$objRapidMail->delete_recipient($strEmail);
				$this->log('The e-mail adress "' . $strEmail . '" has successfully been removed from rapidmail.de (recipient list ID: ' . $objRow->list_id . ')!', 'RapidmailRecipientsSynchronizer removeRecipientFromRapidmail()', TL_GENERAL);
			}
			catch(Exception $e)
			{
				$this->logErrors('onRemove', $e->getMessage(), $strEmail, $channel, $objRow->list_id, $objRow->sendErrorTo);
			}
		}
	} 
  
  
	/**
	 * Log error message and send it via e-mail if activated
	 * @param string
	 * @param string
	 * @param string
	 * @param integer
	 * @param integer
	 * @param string
	 */ 
	private function logErrors($strMode, $strErrorMsg, $strEmail, $intChannel=0, $intRecipientListID=0, $strSendErrorTo='')
	{
		// message
		$strLogMessage = '';
  
		switch($strMode)
		{
			case 'onSend':
				$strLogMessage =	'An error occured while trying to send a new recipient to rapidmail.de!' . "\n" .
                          			'The error message from the API was: "' . $strErrorMsg . "\"\n" .
                          			'The affected e-mail adress is: "' . $strEmail . "\"\n" .
                          			'The affected newsletter channel ID is: ' . $intChannel . "\n" .
                          			'The affected rapidmail.de recipient list ID is: ' . $intRecipientListID;
			break;
      
			case 'onRemove':
				$strLogMessage =	'An error occured while trying to remove a recipient from rapidmail.de!' . "\n" .
                          			'The error message from the API was: "' . $strErrorMsg . "\"\n" .
                          			'The affected e-mail adress is: "' . $strEmail . "\"\n" .
                          			'The affected newsletter channel ID is: ' . $intChannel . "\n" .
                          			'The affected rapidmail.de recipient list ID is: ' . $intRecipientListID;
			break;
		}
    
    	// log the message
    	$this->log($strLogMessage, 'RapidmailRecipientsSynchronizer logErrors()', TL_ERROR);
  
    	// check if there's an e-mail adress defined to inform about the errors via e-mail
    	if(strlen($strSendErrorTo))
    	{
			$objEmail = new Email();
			$objEmail->subject = 'An error occured while trying to synchronize to rapidmail.de';
			$objEmail->text = $strLogMessage;
			$objEmail->sendTo($strSendErrorTo);
		}
	}
}

?>